package cn.itrip.auth.service;

import cn.itrip.comment.RedisAPI;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送接口的实现
 * @author hduser
 *
 */
@Service("mailService")
public class MailServiceImpl implements MailService {

	@Resource
	private RedisAPI redisAPI;
	@Resource
	private SimpleMailMessage activationMailMessage;
	@Resource
	JavaMailSender javaMailSender;

	/**
	 * 发送注册激活邮件
	 */
	@Override
	public void sendActivationMail(String mailTo, String activationCode) {

		try {
			MimeMessage message = javaMailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message,true);
			helper.setSubject("【itrip】请激活您的账户");
			helper.setFrom("hn95184726@163.com");
			helper.setTo(mailTo);
			helper.setText("您已经通过验证，但还未激活。点击<a href='http://localhost:8080/auth/api/activate?user="+mailTo+"&code="+activationCode+"'>立即激活</a>邮箱",true);
			javaMailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		/*activationMailMessage.setTo(mailTo);
		activationMailMessage.setText("注册邮箱："+mailTo +"  激活码："+activationCode);
		mailSender.send(activationMailMessage);*/
		this.saveActivationInfo("activation:"+mailTo, activationCode);
	}

	/**
	 * 保存激活信息
	 * 
	 * @param key
	 * @param value
	 */
	private void saveActivationInfo(String key, String value) {
		redisAPI.set(key, 30*60, value);
	}
}
